﻿using Max.PH5_2103A.Shopping.Frame.Domain.EFCore_DbFirst;
using Max.PH5_2103A.Shopping.Frame.IRepository;
using Max.PH5_2103A.Shopping.Frame.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH5_2103A.Shopping.Frame.Service
{
    public class SKUService : BaseService<TbProductSku>, ISKUService
    {
        ISKURepository _repository;
        IBrandRepository _brandRepository;
        ICategoryRepository _categoryRepository;
        ISPUSpecRepository _spuSpecRepository;
        ISKUImageRepository _imageRepository;
        public SKUService(ISKURepository repository, IUnitOfWork unitOfWork, IBrandRepository brandRepository, ICategoryRepository categoryRepository, ISPUSpecRepository spuSpecRepository, ISKUImageRepository imageRepository) : base(repository, unitOfWork)
        {
            _repository = repository;
            _brandRepository = brandRepository;
            _categoryRepository = categoryRepository;
            _spuSpecRepository = spuSpecRepository;
            _imageRepository = imageRepository;
        }

        //这个方法，同时加载分类、品牌、商品数据
        public dynamic LoadCategorBrandSKU()
        {
            //商品数据
            var skus = _repository.GetAll().Select(x => new { x.Name, x.InPrice, x.Id, x.SaleNumber, x.SalePrice }); ;
            //品牌数据
            var brands = _brandRepository.GetAll();
            //分类数据
            var categories = _categoryRepository.GetAll();

            return new { skus, brands, categories };
        }

        /// <summary>
        /// 根据SKUId获取sku信息、图片信息及对应的spu的规格信息
        /// </summary>
        /// <param name="id"></param>
        public dynamic GetSkuDetailById(string id)
        {
            //1、获取sku的基本信息
            var sku = _repository.GetAll().Where(x => x.Id.ToString().Equals(id)).FirstOrDefault();

            //2、获取sku的对应图片信息(暂时数据表中没有图片)
            var images = _imageRepository.GetAll().Where(x => x.Skuid == sku.Id);

            //3、获取sku对的spu的规格信息
            var data = _spuSpecRepository.GetAll().Where(x => x.SpuId == sku.SpuId).ToList(); //去spu规格及规格值表中根据spuid查找对应的规格

            //去重
            var specName = data.DistinctBy(x => x.SpecName).Select(x => x.SpecName).ToList();

            var specs = from a in specName
                        select new
                        {
                            SpecName = a,
                            SpecValues = data.Where(x => x.SpecName.Equals(a)).Select(x => x.SpecValue).ToList()
                        };

            return new { sku,images,specs};
        }
    }
}
